package node

import (
	corev1 "k8s.io/api/core/v1"
	"kubeimooc/model/base"
	node_res "kubeimooc/model/node/response"
)

type NodeK8s2Res struct {
}

/*
*
获取node节点的状态
*/
func getNodeStatus(nodeConditions []corev1.NodeCondition) string {
	nodeStaus := "NotReady"
	for _, condition := range nodeConditions {
		if condition.Type == "Ready" && condition.Status == "True" {
			nodeStaus = "Ready"
			break
		}
	}
	return nodeStaus
}

/*
*
获取nodeIp
*/
func getNodeIp(addresses []corev1.NodeAddress, addressType corev1.NodeAddressType) string {
	for _, item := range addresses {
		if item.Type == addressType {
			return item.Address
		}
	}
	return "<none>"
}

/*
*
map转list
*/
func mapToList(m map[string]string) []base.ListMapItem {
	items := make([]base.ListMapItem, 0)
	for k, v := range m {
		items = append(items, base.ListMapItem{
			Key:   k,
			Value: v,
		})
	}
	return items
}

/*
*
k8s的node信息转成系统的node的信息
*/
func (n *NodeK8s2Res) GetNodeDetail(nodeK8s corev1.Node) node_res.Node {
	nodeRes := n.GetNodeResItem(nodeK8s)
	//计算label 和taint
	nodeRes.Taints = nodeK8s.Spec.Taints
	nodeRes.Labels = mapToList(nodeK8s.Labels)
	return nodeRes
}

/*
*
处理node的通用信息
*/
func (n *NodeK8s2Res) GetNodeResItem(nodeK8s corev1.Node) node_res.Node {
	nodeInfo := nodeK8s.Status.NodeInfo
	return node_res.Node{
		Name:             nodeK8s.Name,
		Status:           getNodeStatus(nodeK8s.Status.Conditions),
		Age:              nodeK8s.CreationTimestamp.Unix(),
		InternalIp:       getNodeIp(nodeK8s.Status.Addresses, corev1.NodeInternalIP),
		ExternalIp:       getNodeIp(nodeK8s.Status.Addresses, corev1.NodeExternalIP),
		Version:          nodeInfo.KubeletVersion,
		OsImage:          nodeInfo.OSImage,
		KernelVersion:    nodeInfo.KernelVersion,
		ContainerRuntime: nodeInfo.ContainerRuntimeVersion,
		//Labels:           nil,
		//Taints:           nil,
	}
}
